package hnet

import (
	"errors"
	"fmt"
	"haruhi/hiface"
	"sync"
)

/*
连接管理模块
*/
type ConnManager struct {
	connections map[uint32]hiface.IConnection // 管理的连接信息
	connLock   sync.RWMutex                  // 读写链接的读写锁
}

/*
新建连接管理
*/
func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]hiface.IConnection),
	}
}

// add connection
func (connMgr *ConnManager) Add(conn hiface.IConnection)  {
	// 保护共享资源，加锁
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	// 添加连接
	connMgr.connections[conn.GetConnID()] = conn

	fmt.Println("connection add to ConnManager successfully: conn num = ", connMgr.Len())
}

func (connMgr *ConnManager) Remove(conn hiface.IConnection) {
	// 保护共享资源，加锁
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	delete(connMgr.connections, conn.GetConnID())

	fmt.Println("connection remove ConnID = ",conn.GetConnID(), " successfully: conn num = ", connMgr.Len())
}

func (connMgr *ConnManager) Get(connID uint32) (hiface.IConnection, error) {
	// 保护共享资源，加锁
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	if conn, ok := connMgr.connections[connID]; ok {
		return conn, nil
	} else {
		return nil, errors.New("connection not found")
	}
}

func (connMgr *ConnManager) Len() int {
	return len(connMgr.connections)
}

func (connMgr *ConnManager) ClearConn()  {
	// 保护共享资源，加锁
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	for ConnID, conn := range connMgr.connections {
		conn.Stop()
		delete(connMgr.connections, ConnID)
	}

	fmt.Println("Clear all connections successfully: conn num = ", connMgr.Len())
}